import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LogisticRegression  # 逻辑回归模型
from sklearn.metrics import accuracy_score  # 准确率

data = pd.read_csv('examdata.csv')

# 可视化数据
mask = data.loc[:, 'Pass'] == 1
plt.figure(figsize=(10, 10))
passed = plt.scatter(data.loc[:, 'Exam1'][mask], data.loc[:, 'Exam2'][mask], )
failed = plt.scatter(data.loc[:, 'Exam1'][~mask], data.loc[:, 'Exam2'][~mask], )
plt.title('Exam1 and Exam2')
plt.xlabel('Exam1')
plt.ylabel('Exam2')
# 实例名称
plt.legend((passed, failed), ('Pass', 'Fail'))
# plt.show()

# 训练模型
X = data.drop(['Pass'], axis=1)
Y = data.loc[:, 'Pass']
exam1 = data.loc[:, 'Exam1']
exam2 = data.loc[:, 'Exam2']

# 确认维度
# print(X.shape)
# print(Y.shape)

# 创建新数据
X1 = exam1
X2 = exam2
X1_2 = X1 * X1
X2_2 = X2 * X2
X1_X2 = X1 * X2

X_new = {'X1': X1, 'X2': X2, 'X1_2': X1_2, 'X2_2': X2_2, 'X1_X2': X1_X2}
X_new = pd.DataFrame(X_new)
print(X_new)

# 训练模型
model = LogisticRegression()
model.fit(X_new, Y)
Y_predict = model.predict(X_new)
print(accuracy_score(Y, Y_predict))

# 画图

print(model.intercept_, model.coef_)
theta0 = model.intercept_[0]
theta1 = model.coef_[0][0]
theta2 = model.coef_[0][1]
theta3 = model.coef_[0][2]
theta4 = model.coef_[0][3]
theta5 = model.coef_[0][4]


X1_new = X1.sort_values()  # 对X1进行排序

a = theta4
b = theta5 * X1_new + theta2
c = theta0 + theta1 * X1_new + theta3 * X1_new * X1_new
X2_new_boundary = (-b + np.sqrt(b * b - 4 * a * c)) / (2 * a)

# 先排序，防止线交叉


plt.plot(X1_new, X2_new_boundary)
plt.show()
